package com.cardone.generator.template;

import com.cardone.common.template.util.*;
import com.cardone.generator.mapper.*;
import com.google.common.collect.*;
import freemarker.ext.beans.*;
import freemarker.template.*;
import lombok.*;
import lombok.experimental.*;
import org.apache.commons.io.*;
import org.springframework.ui.freemarker.*;
import org.springframework.util.*;

import java.io.*;
import java.util.*;

/**
 * 创建索引模板
 *
 * @author yaohaitao
 */
@Getter
@Setter
@Accessors(chain = true)
public class RunCreateIndexTemplate implements RunTemplate {
    private Configuration configuration;

    private List<EntityMapper> entityMapperList;

    private String outputDir;

    @Override
    public void run() throws Exception {
        final String templateString = "${outputDir!}/createIndex.sql";

        final Map<String, Object> contextMap = Maps.newHashMap();

        contextMap.put("outputDir", this.outputDir);

        final String filePathName = TemplateUtils.processString(templateString, contextMap);

        final File file = new File(filePathName);

        if (file.exists()) {
            FileUtils.deleteQuietly(file);
        }

        final String templateName = "createIndex.ftl";

        final freemarker.template.Template template = this.configuration.getTemplate(templateName);

        final Map<String, Object> model = Maps.newHashMap();

        model.put("entityMapperList", this.entityMapperList);

        model.put("statics", BeansWrapper.getDefaultInstance().getStaticModels());

        final String data = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);

        FileUtils.writeStringToFile(file, data);
    }

    @Override
    public List<PoMapper> findListPoMapper() {
        final List<PoMapper> poMapperList = Lists.newArrayList();

        if (CollectionUtils.isEmpty(this.entityMapperList)) {
            return poMapperList;
        }

        for (final EntityMapper entityMapper : this.entityMapperList) {
            poMapperList.add(entityMapper);
        }

        return poMapperList;
    }
}
